import { NavBar, InfiniteScroll, Popup, Toast } from 'antd-mobile'
import { useHistory, useParams } from 'react-router-dom'
import classNames from 'classnames'
import styles from './index.module.scss'

import Icon from '@/components/icon'
import CommentItem from './components/CommentItem'
import CommentFooter from './components/CommentFooter'
import { useEffect, useRef, useState } from 'react'
import {
  getArticleInfo,
  getCommentList,
  followUser,
  unFollowUser,
  likeArticle,
  unLikeArticle,
  collectArticle,
  unCollectArticle,
  addComment,
} from '@/store/actions/article'
import { ArticleDetail } from '@/types/data'
import DOMPurify from 'dompurify'
import highlight from 'highlight.js'
import 'highlight.js/styles/monokai-sublime.css'
import { CommentRes } from '@/types/data'
import CommentInput from './components/CommentInput'
import CommentReply from './components/CommentReply'
import produce from 'immer'
const Article = () => {
  const history = useHistory()
  const { id } = useParams<{ id: string }>()
  // 发送请求，获取文章详情
  const [article, setArticle] = useState<ArticleDetail>({} as ArticleDetail)

  useEffect(() => {
    // 获取文章详情
    getArticleInfo(id).then((res) => {
      setArticle(res.data.data)
    })
  }, [id])

  useEffect(() => {
    highlight.configure({
      // 忽略警告
      ignoreUnescapedHTML: true,
    })
    // 代码高亮
    highlight.highlightAll()
  }, [article])

  const authorRef = useRef<HTMLDivElement>(null)
  const wrapperRef = useRef<HTMLDivElement>(null)

  // 一进来，需要给wrapperRef注册滚动事件
  const [showAuthor, setShowAuthor] = useState(false)
  useEffect(() => {
    const wrapperDOM = wrapperRef.current!
    const authorDOM = authorRef.current!
    const handleScroll = () => {
      const rect = authorDOM.getBoundingClientRect()
      if (rect.top < 0) {
        setShowAuthor(true)
      } else {
        setShowAuthor(false)
      }
    }
    wrapperDOM.addEventListener('scroll', handleScroll)
    return () => {
      wrapperDOM.removeEventListener('scroll', handleScroll)
    }
  }, [])

  const [commentRes, setCommentRes] = useState<CommentRes>({
    results: [],
    total_count: 100,
    last_id: '',
    end_id: '',
  } as CommentRes)
  const loadMore = async () => {
    const res = await getCommentList(id, commentRes.last_id)
    setCommentRes({
      ...res.data.data,
      results: [...commentRes.results, ...res.data.data.results],
    })
  }
  // console.log(commentRes.results.length)
  const hasMore = commentRes.results.length < commentRes.total_count

  // 切换关注用户
  const toggleFollow = async () => {
    // 判断用户是否关注
    if (article.is_followed) {
      // 取消关注
      // 发送请求
      await unFollowUser(article.aut_id)
    } else {
      // 关注
      // 发送请求
      await followUser(article.aut_id)
    }
    // 更新文章信息
    setArticle({
      ...article,
      is_followed: !article.is_followed,
    })
  }

  const toggleAttitude = async (attitude: number) => {
    console.log(attitude)
    if (attitude === -1) {
      await likeArticle(article.art_id)
    } else {
      await unLikeArticle(article.art_id)
    }
    // 修改文章的态度
    setArticle({
      ...article,
      attitude: attitude === -1 ? 1 : -1,
    })
  }

  const toggleCollect = async (is_collected: boolean) => {
    if (is_collected) {
      // 取消收藏
      // 发送请求
      await collectArticle(article.art_id)
    } else {
      // 收藏
      // 发送请求
      await unCollectArticle(article.art_id)
    }
    // 修改文章的收藏状态
    setArticle({
      ...article,
      is_collected: !article.is_collected,
    })
  }

  const [isComment, setIsComment] = useState(false)
  const commentRef = useRef<HTMLDivElement>(null)
  const goComment = () => {
    const wrapperDOM = wrapperRef.current!
    const commentDOM = commentRef.current!
    if (!isComment) {
      // 跳转到评论的地方
      wrapperDOM.scrollTo(0, commentDOM.offsetTop - 45)
    } else {
      // 跳转到顶部
      wrapperDOM.scrollTo(0, 0)
    }
    setIsComment(!isComment)
  }

  const [commentShow, setCommentShow] = useState(false)
  const hideComment = () => {
    setCommentShow(false)
  }
  const showComment = () => {
    setCommentShow(true)
  }

  // 发表评论
  const addCommentFn = async (value: string) => {
    // console.log('value', value)
    // 发送请求，添加评论
    const res = await addComment(article.art_id, value)
    // 提示消息
    console.log('res', res)
    Toast.show('评论成功')
    // 关闭弹层
    hideComment()
    // 重新渲染评论
    setCommentRes({
      ...commentRes,
      results: [res.data.data.new_obj, ...commentRes.results],
      total_count: commentRes.total_count + 1,
    })
  }

  // 控制回复的显示隐藏
  const [replyShow, setReplyShow] = useState({
    visible: false,
    comment_id: '',
  })
  const hideReply = () => {
    setReplyShow({
      visible: false,
      comment_id: '',
    })
  }
  const showReply = (comment_id: string) => {
    setReplyShow({
      visible: true,
      comment_id,
    })
  }

  // 让评论的数量+1
  const addReplyCount = (comment_id: string) => {
    setCommentRes(
      produce((draft: CommentRes) => {
        const obj = draft.results.find((item) => item.com_id === comment_id)
        obj!.reply_count += 1
      })
    )
  }

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar
          onBack={() => history.go(-1)}
          right={
            <span>
              <Icon type="icongengduo" />
            </span>
          }
        >
          {showAuthor && (
            <div className="nav-author">
              <img src={article.aut_photo} alt="" />
              <span className="name">{article.aut_name}</span>
              <span
                className={classNames(
                  'follow',
                  article.is_followed ? 'followed' : ''
                )}
                onClick={toggleFollow}
              >
                {article.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {/* 文章详情和评论 */}
        <div className="wrapper" ref={wrapperRef}>
          <div className="article-wrapper">
            <div className="header">
              <h1 className="title">{article.title}</h1>

              <div className="info">
                <span>{article.pubdate}</span>
                <span>{article.read_count} 阅读</span>
                <span>{article.comm_count} 评论</span>
              </div>

              <div className="author" ref={authorRef}>
                <img src={article.aut_photo} alt="" />
                <span className="name">{article.aut_name}</span>
                <span
                  className={classNames(
                    'follow',
                    article.is_followed ? 'followed' : ''
                  )}
                  onClick={toggleFollow}
                >
                  {article.is_followed ? '已关注' : '关注'}
                </span>
              </div>
            </div>

            <div className="content">
              <div
                className="content-html dg-html"
                dangerouslySetInnerHTML={{
                  __html: DOMPurify.sanitize(article.content),
                }}
              />
              <div className="date">发布文章时间：{article.pubdate}</div>
            </div>
          </div>

          <div className="comment" ref={commentRef}>
            <div className="comment-header">
              <span>全部评论（{commentRes.results.length}）</span>
              <span>{article.like_count} 点赞</span>
            </div>

            <div className="comment-list">
              {commentRes.results.map((item) => (
                <CommentItem
                  showReply={showReply}
                  type="normal"
                  comment={item}
                  key={item.com_id}
                />
              ))}

              <InfiniteScroll hasMore={hasMore} loadMore={loadMore} />
            </div>
          </div>
        </div>

        {/* 底部评论栏 */}
        <CommentFooter
          type="normal"
          article={article}
          toggleAttitude={toggleAttitude}
          toggleCollect={toggleCollect}
          goComment={goComment}
          showComment={showComment}
        />

        {/* 弹层 */}
        <Popup visible={commentShow} position="right" destroyOnClose>
          <CommentInput
            hideComment={hideComment}
            addComment={addCommentFn}
          ></CommentInput>
        </Popup>

        <Popup visible={replyShow.visible} position="right" destroyOnClose>
          <CommentReply
            hideReply={hideReply}
            comment={commentRes.results.find(
              (item) => item.com_id === replyShow.comment_id
            )}
            addReplyCount={addReplyCount}
          ></CommentReply>
        </Popup>
      </div>
    </div>
  )
}

export default Article
